package com.weishuang.monitor.leader.config.security.handler;

import cn.hutool.json.JSONUtil;
import com.weishuang.monitor.leader.commons.entity.Result;
import com.weishuang.monitor.leader.commons.enums.RCODE;
import com.weishuang.monitor.leader.commons.utils.ResultUtils;
import com.weishuang.monitor.leader.commons.utils.UserUtils;
import com.weishuang.monitor.leader.config.dto.CustomUserDetails;
import com.weishuang.monitor.leader.entity.SysUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        CustomUserDetails user = UserUtils.getUser();
        SysUser sysUser = new SysUser();
        sysUser.setId(user.getId());
        sysUser.setRealName(user.getRealName());
        Result success = ResultUtils.success(RCODE.LOGIN_SUCCESS, sysUser);
        httpServletResponse.setStatus(200);
        httpServletResponse.setHeader("Content-type","application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(JSONUtil.toJsonPrettyStr(success));
    }
}
